package com.heima.user.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.kafka.common.protocol.types.Field;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.sql.Wrapper;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper,ApUser> implements ApUserService {
    /**
     * 登录
     *
     * @param loginDto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto loginDto) {
        /*//1、判断用户为登录用户还是游客
            //1.1获取请求体，均不为空则为登录用户
        if(StringUtils.isNotEmpty(loginDto.getPhone()) && StringUtils.isNotEmpty(loginDto.getPassword())){
        //2、如果是登录用户：校验用户和密码，返回用户信息和token
            //2.1根据手机号查询用户信息
            *//**
            LambdaQueryWrapper<ApUser> lqw = new LambdaQueryWrapper<>();
            lqw.eq(ApUser::getPhone,loginDto.getPhone());
            ApUser user = getOne(lqw);  化简如下：
             *//*
            ApUser user = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, loginDto.getPhone()));
            //2.2如果查询用户为空，则返回“用户不存在”
            if(user == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }else {
            //2.3校验密码（输入密码+盐->MD5加密）
                String inputPasswordWithDigest = DigestUtils.md5DigestAsHex((loginDto.getPassword() + user.getSalt()).getBytes());
                //2.3.1密码不相等则返回“密码错误”
                if(!user.getPassword().equals(inputPasswordWithDigest)){
                    return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
                }
            }
            //2.4返回用户信息和token
            Map<String,Object> msg = new HashMap<>();
            msg.put("id",user.getId());
            msg.put("name",user.getName());
            msg.put("phone",user.getPhone());

            Map<String, Object> map = new HashMap<>();
            map.put("user",msg);
            map.put("token",AppJwtUtil.getToken(Long.valueOf(user.getId())));
            return ResponseResult.okResult(map);
        //3、均为空则为游客
        }else if(StringUtils.isEmpty(loginDto.getPhone()) && StringUtils.isEmpty(loginDto.getPassword())){
            //3.1如果是游客：直接返回token
            Map<String, Object> map = new HashMap<>();
            map.put("token",AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }else {
            //只输入一个参数返回“缺少参数”
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }*/


        //1、判断用户是登录用户还是游客
            //1.1输入参数均不为空则为登录用户
        if(StringUtils.isNotEmpty(loginDto.getPhone()) && StringUtils.isNotEmpty(loginDto.getPassword())){
        //2、如果是登录用户，则验证用户和密码，通过返回用户信息和token
            //2.1根据手机号查询用户信息以验证用户和密码
            ApUser user = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, loginDto.getPhone()));
            //2.2如果用户为空，则返回“用户不存在”
            if(user == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }else {
            //2.3验证密码（输入密码+盐 -> md5加密）
                String inputPasswordWithDigest = DigestUtils.md5DigestAsHex((loginDto.getPassword() + user.getSalt()).getBytes());
                //2.3.1密码不匹配则返回“密码错误”
                if(!user.getPassword().equals(inputPasswordWithDigest)){
                    return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
                }
            }
            //2.4返回用户信息和token
            Map<String,Object> users = new HashMap<>();
            users.put("id",user.getId());
            users.put("name",user.getName());
            users.put("phone",user.getPhone());

            Map<String,Object> map = new HashMap<>();
            map.put("user",users);
            map.put("token",AppJwtUtil.getToken(Long.valueOf(user.getId())));
            return ResponseResult.okResult(map);

        }else if(StringUtils.isEmpty(loginDto.getPhone()) && StringUtils.isEmpty(loginDto.getPassword())){
        //3、输入参数均为空则为游客，直接返回token
            Map<String,Object> map = new HashMap<>();
            map.put("token",AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
    }
}
